<?php
namespace Core\Event;
use Phalcon\Di\Injectable;
class Application extends Injectable
{
    protected function _getAnnotations() {
        $annotations = $this->annotations->get($this->dispatcher->getControllerClass());
        $annotations = array_merge(
            $annotations->getClassAnnotations()->getAnnotations(),
            $annotations->getMethodsAnnotations()[$this->dispatcher->getActiveMethod()]->getAnnotations()
        );
        return $annotations;
    }

    protected function _resolveAnnotation($event) {
        if($annotations = $this->_getAnnotations()) {
            $eventsSort = [
                'Input',
                'Cache',
                'View',
                'Output',
            ];
            foreach ($annotations as $annotation) {
                $name = ucfirst($annotation->getName());
                if(in_array($name, $eventsSort)) {
                    $eventsSort[$name] = $annotation;
                }
            }
            foreach ($eventsSort as $name => $annotation) {
                $class = "\\Core\\Event\\Application\\Annotation\\{$name}";
                if(!class_exists($class)) {
                    continue;
                }
                $object = new $class($annotation);
                if(method_exists($object, $event->getType())) {
                    if(!$object->{$event->getType()}($event)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //request send cache
    public function beforeHandleRequest($event, $application) {
        return $this->_resolveAnnotation($event);
        return true;
    }

    //save view cache
    public function viewRender($event) {
        return $this->_resolveAnnotation($event);
    }

    //save cache
    public function afterHandleRequest($event) {
        return $this->_resolveAnnotation($event);
    }

    //before response
    public function beforeSendResponse($event) {
        return $this->_resolveAnnotation($event);
    }

    //after start module event
    public function afterStartModule($event, $application, $bootstrap) {
        $this->view->setViewsDir("{$bootstrap->getModuleName()}/views");
        $this->eventsManager->attach('dispatch', $bootstrap);
        return true;
    }
}